const db = require('../../lib/conn_oracle')
const exists = require('../../util/exists')

//查询权限组信息
exports.getAuthoritysInfo = (req,res)=>{
    let authoritySql = `select * from c##wxw.vue_xfjcauthoritys order by id`
    let datas
    async function fun(){
        let authoritys = await db.search2(authoritySql)
        datas = {authoritys}
        res.json({
            status:1,
            msg:"查询成功",
            datas
        })
    }
    fun()
}

//查询已有权限
exports.hasDirs = (req,res)=>{
    // console.log(req.query);
    let {id} = req.query
    id = Number(id)
    // console.log(id);
    let hasDirsSql = `select *
                      from c##wxw.vue_xfjcauthority_dirs_middle
                      where authorityid = ${id}
                      order by authorityid,dirid
                     `
    let datas 
    async function fun(){
        let hasDirs = await db.search2(hasDirsSql)
        datas = {hasDirs}
        res.json({
            status:1,
            msg:"查询成功",
            datas
        })
    }
    fun()
}

//更新、新增、删除权限组
exports.editAuthoritys = async (req,res)=>{
    let {submitType,submitForm} = req.body
    let {ID,AUTHORITYNAME,REMARK} = submitForm
    // console.log(submitType);
    // console.log(submitForm);
    let resDatas
    let handleSql
    let handleData
    let msg
    let submitTypeStr
    let status
    /**
     * 数据库处理函数
     * @param {String} sql  sql语句
     * @param {Array} data  参数（以数组形式传递，批量处理使用嵌套数组）
     */
    const cudFun = async (sql,data)=>{
        let newAuthoritys = await db.writeTab(sql,data)
        resDatas = {newAuthoritys}
        msg = resDatas.newAuthoritys.errorNum ? `${submitTypeStr}失败，错误代码：ORA-` + resDatas.newAuthoritys : `${submitTypeStr}成功`
        status = 1
        return {
            status,
            msg,
            resDatas
        } 
    }

    if(submitType === "update"){
        submitTypeStr = "更新"
        handleData = [AUTHORITYNAME,REMARK,ID]
        handleSql = `
                     update c##wxw.vue_xfjcauthoritys
                     set
                     authorityname = :AUTHORITYNAME,
                     remark = :REMARK
                     where id = :ID
                    `
        let newAuthoritys = await cudFun(handleSql,handleData)
        res.json(newAuthoritys)
    }
    if(submitType === "add"){
        submitTypeStr = "新增"
        handleData = [AUTHORITYNAME,REMARK]
        handleSql = `
                     insert into c##wxw.vue_xfjcauthoritys(id,authorityname,remark)
                     values('',:AUTHORITYNAME,:REMARK)
                    `
        let newAuthoritys = await cudFun(handleSql,handleData)
        res.json(newAuthoritys)
    }
    if(submitType === "delete"){
        submitTypeStr = "删除"
        handleData = [ID]
        handleSql = `delete c##wxw.vue_xfjcauthoritys where id = :ID`
        let newAuthoritys = await cudFun(handleSql,handleData)
        if(newAuthoritys.msg.includes("失败")){
            newAuthoritys.msg = "权限组删除失败"
            res.json(newAuthoritys)
        }else{
            handleSql = `delete c##wxw.vue_xfjcauthority_dirs_middle where authorityid = :ID`
            let newAuthoritys = await cudFun(handleSql,handleData)
            if(newAuthoritys.msg.includes("失败")){
                newAuthoritys.msg = "目录所在权限组删除失败"
                res.json(newAuthoritys)
            }else{
                handleSql = `delete c##wxw.vue_xfjcrole_authority_middle where authorityid = :ID`
                let newAuthoritys = await cudFun(handleSql,handleData)
                if(newAuthoritys.msg.includes("失败")){
                    newAuthoritys.msg = "角色所分配权限组删除失败"
                    res.json(newAuthoritys) 
                }else{
                    newAuthoritys.msg = "权限组删除成功"           
                    res.json(newAuthoritys)
                }
            }
        }       
    }     
}

//获取目录及中间表信息
exports.getDirsAndMidInfo = async (req,res)=>{
    // console.log(req.body)    
    let {id} = req.body
    // id = Number(id)  
    let dirsAndMidSql = `select d.*
                            ,adm.id as admid,adm.authorityid
                            ,case when adm.is_add is not null then adm.is_add else 0 end as is_add
                            ,case when adm.is_update is not null then adm.is_update else 0 end as is_update
                            ,case when adm.is_del is not null then adm.is_del else 0 end as is_del
                        from c##wxw.vue_xfjcDirs d
                        left join c##wxw.vue_xfjcauthority_dirs_middle adm
                        on adm.dirid = d.id
                        and authorityid = :id
                        order by d.dirlevel
                        `
    let resDatas
    let status
    let msg
    try{
        let dirsAndMid = await db.search(dirsAndMidSql,[id])
        resDatas = {dirsAndMid}
        msg = "查询成功"
        status = 1
        res.json({
            status,
            msg,
            resDatas
        })
    }catch(err){
        console.log(err)
        msg = "查询失败"
        status = 0 
        res.json({
            status,
            msg,
            resDatas 
        })
    }                    
}

//权限变更
exports.changeAuthority = async (req,res)=>{    
    let {submitForm} = req.body    
    let {needAdd,needDel,needUpdate} = submitForm
    // console.log(needAdd)
    // console.log(needDel)
    // console.log(needUpdate)
    let options = {
        autoCommit: true,
    }
    let addResDatas
    let delResDatas
    let updateResDatas
    let addDatas = needAdd ? needAdd : []
    let delDatas = needDel ? needDel : []
    let updateDatas = needUpdate ? needUpdate : []
    let addSql = `insert into c##wxw.vue_xfjcauthority_dirs_middle(id,authorityid,dirid,is_add,is_update,is_del)
                  values('',:authorityId,:DIRID,:IS_ADD,:IS_UPDATE,:IS_DEL)`
    let delSql = `delete c##wxw.vue_xfjcauthority_dirs_middle
                  where id = :ADMID`
    let updateSql = `update c##wxw.vue_xfjcauthority_dirs_middle
                     set is_add = :IS_ADD,
                         is_update = :IS_UPDATE,
                         is_del = :IS_DEL
                     where id = :ADMID`
    let addMsg
    let addStatus
    let delMsg
    let delStatus
    let updateMsg
    let updateStatus
    if(addDatas.length){
        let newAuthoritys = await db.writeManyTab2(addSql,addDatas,options)
        addResDatas = {newAuthoritys}
        addMsg = addResDatas.newAuthoritys.errorNum? `新增权限失败，错误代码：ORA-` + addResDatas.newAuthoritys : `新增权限成功`
        addStatus = addResDatas.newAuthoritys.errorNum ? 0 : 1
    }   
    if(delDatas.length){
        let newAuthoritys = await db.writeManyTab2(delSql,delDatas,options)
        delResDatas = {newAuthoritys}
        delMsg = delResDatas.newAuthoritys.errorNum? `删除权限失败，错误代码：ORA-` + delResDatas.newAuthoritys : `删除权限成功`
        delStatus = delResDatas.newAuthoritys.errorNum? 0 : 1 
    }
    if(updateDatas.length){
        let newAuthoritys = await db.writeManyTab2(updateSql,updateDatas,options)
        updateResDatas = {newAuthoritys}
        updateMsg = updateResDatas.newAuthoritys.errorNum? `更新权限失败，错误代码：ORA-` + updateResDatas.newAuthoritys : `更新权限成功` 
        updateStatus = updateResDatas.newAuthoritys.errorNum? 0 : 1
    }
    
    if(addDatas.length && delDatas.length && updateDatas.length){
       res.json({
            status:addStatus && delStatus && updateStatus ? 1 : 0,
            msg:addMsg + delMsg + updateMsg,
            resDatas:{addResDatas,delResDatas,updateResDatas}
        }) 
    }
    if(addDatas.length && delDatas.length && !updateDatas.length){
        res.json({
            status:addStatus && delStatus? 1 : 0,
            msg:addMsg + delMsg,
            resDatas:{addResDatas,delResDatas}
        }) 
    }
    if(addDatas.length && !delDatas.length && updateDatas.length){
        res.json({
            status:addStatus && updateStatus? 1 : 0,
            msg:addMsg + updateMsg,
            resDatas:{addResDatas,updateResDatas}
        }) 
    }
    if(addDatas.length &&!delDatas.length &&!updateDatas.length){
        res.json({
            status:addStatus? 1 : 0,
            msg:addMsg,
            resDatas:{addResDatas}
        }) 
    }
    if(!addDatas.length && delDatas.length && updateDatas.length){
        res.json({
            status:delStatus && updateStatus? 1 : 0,
            msg:delMsg + updateMsg,
            resDatas:{delResDatas,updateResDatas}
        }) 
    }
    if(!addDatas.length && delDatas.length && !updateDatas.length){
        res.json({
            status:delStatus? 1 : 0,
            msg:delMsg,
            resDatas:{delResDatas}
        }) 
    }
    if(!addDatas.length &&!delDatas.length && updateDatas.length){
        res.json({
            status:updateStatus? 1 : 0,
            msg:updateMsg,
            resDatas:{updateResDatas}
        }) 
    }
    
}
//#region 
// exports.changeAuthority = async (req,res)=>{
//     let {authorityId , submitForm} = req.body
//     let {oldAuth , newAuth} = submitForm   
//     let resDatas 
//     let handleSql
//     let handleData
//     let msg
//     let status
//     let options = {
//         autoCommit: true,
//     }
//     // console.log(authorityId);    
//     // console.log(oldAuth);
//     // console.log(newAuth);
//      /**
//      * 数据库批量处理前数据转换
//      * @param {Array} arr 转换嵌套数组前的数组
//      * @param {Number} authId 权限组ID
//      */
//     const dataHanding = (authId,arr)=>{
//         let newArr = []
//         for(let i = 0;i < arr.length;i++){           
//             newArr.push([Number(authId),Number(arr[i])])          
//         }
//         // console.log(newArr)        
//         return newArr
//     }
//     /**
//      * 数据库处理
//      * @param {String} changeType 修改类型：singleAdd(单个新增)、singleDel(单个权限删除)、AuthDel(同一权限组内所有权限均删除，变更后已无任何权限)、
//      *                                     batchAdd(批量新增)、batchDel(批量删除)
//      * @param {Array} data 数据，单个处理以数组形式传入、批量处理以嵌套数组形式传入
//      * @param {Object} options ORACLE处理配置，批量处理时使用
//      */
//     const authChange = async (changeType,data,ops=options)=>{
//         if(changeType === "AuthDel"){
//             handleSql = `delete c##wxw.vue_xfjcauthority_dirs_middle where authorityid = :authorityId`
//         }else{
//             handleSql = changeType.includes("Add") ? `insert into c##wxw.vue_xfjcauthority_dirs_middle(id,authorityid,dirid) 
//                                                       values('',:authorityId,:dirid)
//                                                      `
//                                                    : `delete c##wxw.vue_xfjcauthority_dirs_middle 
//                                                       where authorityid = :authorityId
//                                                         and dirid = :dirid
//                                                      `
//         }  
//         let changeTypeStr = changeType.includes("Del") ? "删除" : "新增"
//         let newAuthoritys = (changeType.includes("single") ||  changeType === "AuthDel") ? await db.writeTab(handleSql,data) : await db.writeManyTab2(handleSql,data,ops)                        
//         resDatas = {newAuthoritys}            
//         msg = (resDatas.newAuthoritys.errorNum || resDatas.newAuthoritys.code ) ? `${changeTypeStr}权限失败，错误代码：ORA-` + resDatas.newAuthoritys  
//                                                                                 : `${changeTypeStr}权限成功`
//         status = (resDatas.newAuthoritys.errorNum || resDatas.newAuthoritys.code ) ? 0 : 1
//         return {
//             status,
//             resDatas,
//             msg
//         }
//     }

//     if(!oldAuth && newAuth){
//         handleData = dataHanding(authorityId,newAuth)            
//         let newAuthoritys = await authChange("batchAdd",handleData) // msg = "原无权限，现新增" 
//         res.json(newAuthoritys)
//     }else if(oldAuth && !newAuth){
//         handleData = [Number(authorityId)]     
//         let newAuthoritys = await authChange("AuthDel",handleData) // msg = "原有权限，后无所有权限，删除" 
//         res.json(newAuthoritys)
//     }else{
//     //    长度相同，也需要判断权限明细是否有不同    
//        let needDel = exists.exists(oldAuth,newAuth) //须删除
//        let needAdd = exists.exists(newAuth,oldAuth) //须增加
//        let ctStr 
//     //    console.log(needDel);
//     //    console.log(needAdd);       
//        if(!needDel.length && !needAdd.length){
//             msg = "权限未作修改"           
//             status = 0
//             res.json({
//                 status,
//                 msg
//            })
//        }else if((needDel.length && !needAdd.length) || (!needDel.length && needAdd.length)){
//             if(needDel.length && !needAdd.length && needDel.length > 1){
//                 ctStr = "batchDel"
//                 handleData = dataHanding(authorityId,needDel) 
//             }else if(needDel.length && !needAdd.length && needDel.length === 1){
//                 ctStr = "singleDel"
//                 handleData = [Number(authorityId),Number(needDel[0])]
//             }else if(!needDel.length && needAdd.length && needAdd.length > 1){
//                 ctStr = "batchAdd"
//                 handleData = dataHanding(authorityId,needAdd) 
//             }else if(!needDel.length && needAdd.length && needAdd.length === 1){
//                 ctStr = "singleAdd"
//                 handleData = [Number(authorityId),Number(needAdd[0])]
//             } 
//             let newAuthoritysDel = await authChange(ctStr,handleData)
//             if(newAuthoritysDel.msg.includes("失败")){
//                 msg = "权限修改失败"           
//                 status = 0
//                 res.json({
//                     status,
//                     msg
//                 })
//             }else{
//                 msg = "权限修改成功"           
//                 status = 1
//                 res.json({
//                     status,
//                     msg
//                 })
//             }
//        }else{
//             //需要缩减和增加权限(先增加，后删除)
//             ctStr = needAdd.length > 1 ? "batchAdd" : "singleAdd"
//             handleData = needAdd.length > 1 ? dataHanding(authorityId,needAdd) : [Number(authorityId),Number(needAdd[0])]
//             let newAuthoritysAdd = await authChange(ctStr,handleData)
//             if(newAuthoritysAdd.msg.includes("失败")){
//                 msg = "权限修改失败"           
//                 status = 0
//                 res.json({
//                     status,
//                     msg
//                 })
//             }else{
//                 ctStr = needDel.length > 1 ? "batchDel" : "singleDel"
//                 handleData = needDel.length > 1 ? dataHanding(authorityId,needDel) : [Number(authorityId),Number(needDel[0])]
//                 let newAuthoritysDel = await authChange(ctStr,handleData)
//                 if(newAuthoritysDel.msg.includes("失败")){
//                     msg = "权限修改失败"           
//                     status = 0
//                     res.json({
//                         status,
//                         msg
//                     })
//                 }else{
//                     msg = "权限修改成功"           
//                     status = 1
//                     res.json({
//                         status,
//                         msg
//                     })
//                 }
//             }
//        }       
//     }  
    
// }
//#endregion

